#include "MGUI_TextBox.h"
#include "MGUI_Layout.h"
#include "MGUI_Helper.h"

namespace Myway {

	ImplementRTTI(MGUI_TextBox, MGUI_Widget);

	MGUI_TextBox::MGUI_TextBox(MGUI_Widget * _parent)
		: MGUI_Widget(NULL, _parent)
	{
		SetPickFlag(MGUI_PickFlag::None);
		mFont = MGUI_FontManager::Instance()->GetDefaultFont();

		SetOrder(MGUI_Order::Text);
	}

	MGUI_TextBox::~MGUI_TextBox()
	{
	}

	void MGUI_TextBox::SetCaption(const MGUI_String & caption)
	{
		mCaption = caption;

		_updateGlyph();
	}

	const MGUI_String & MGUI_TextBox::GetCaption()
	{
		return mCaption;
	}

	void MGUI_TextBox::SetFont(MGUI_Font * _font)
	{
		mFont = _font;

		_updateGlyph();
	}

	MGUI_Font * MGUI_TextBox::GetFont()
	{
		return mFont;
	}

	int MGUI_TextBox::GetGlyphCount()
	{
		return mGlyphs.Size();
	}

	const MGUI_Glyph * MGUI_TextBox::GetGlyph(int index)
	{
		return mGlyphs[index];
	}

	void MGUI_TextBox::Update()
	{
		SetRect(mGlyphRect);

		MGUI_Widget::Update();
	}

	void MGUI_TextBox::UpdateRenderItem(MGUI_Layout * _layout)
	{
		if (mFont == NULL)
			return ;

		int order = GetAbsOrder();
		float x_base = float(GetAbsRect().x0);
		float y_base = float(GetAbsRect().y0);
		MGUI_Color color = GetColor();
		MGUI_Rect clipRect = GetParentClipRect();

		Texture * skin = NULL;
		MGUI_RenderItem * item = NULL;

		MGUI_RectF myRect, uvRect;

		for (int i = 0; i < mGlyphs.Size(); ++i)
		{
			const MGUI_Glyph * glyph = mGlyphs[i];

			if (glyph->texture != skin)
			{
				item = _layout->GetRenderItem(order, glyph->texture);
				skin = glyph->texture;
			}

			myRect.x0 = x_base + glyph->bearingX;
			myRect.y0 = y_base + glyph->bearingY;
			myRect.x1 = myRect.x0 + glyph->width;
			myRect.y1 = myRect.y0 + glyph->height;
			
			uvRect.x0 = glyph->u0;
			uvRect.y0 = glyph->v0;
			uvRect.x1 = glyph->u1;
			uvRect.y1 = glyph->v1;

			MGUI_RectF _rect, _uv;

			if (MGUI_Helper::Instance()->Clip(_rect, _uv, myRect, uvRect, clipRect))
			{
				item->AddQuad(MGUI_Helper::Instance()->GetQuad(_rect, _uv, color));
			}
			
			x_base += glyph->advance;
		}

	}

	void MGUI_TextBox::_updateGlyph()
	{
		mGlyphs.Clear();

		if (mFont == NULL)
			return ;
		
		mGlyphRect.x0 = 0;
		mGlyphRect.x1 = 0;
		mGlyphRect.y0 = 0;
		mGlyphRect.y1 = (int)mFont->Height();

		int length = mCaption.Length();
		int width = 0;

		for (int i = 0; i < length; ++i)
		{
			MGUI_Char ch = mCaption[i];

			const MGUI_Glyph * glyph = mFont->GetGlyph(ch);
			
			if (glyph == NULL)
			{
				glyph = mFont->GetGlyph(L'*');
			}

			mGlyphs.PushBack(glyph);
			width += (int)glyph->advance;
		}

		mGlyphRect.x1 = width;
	}

}